package com.tqjc.system.core.gate.sdk.callback.impl;

import com.sun.jna.Pointer;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.enums.GateActionEnum;
import com.tqjc.system.common.enums.GateRecordStatusEnum;
import com.tqjc.system.common.enums.GateTypeEnum;
import com.tqjc.system.core.gate.asyn.CarPhotoThread;
import com.tqjc.system.core.gate.constants.GateConstant;
import com.tqjc.system.core.gate.sdk.callback.IPlateCallback;
import com.tqjc.system.core.gate.service.SysGateService;
import com.tqjc.system.core.util.FileUtils;
import com.tqjc.system.system.entity.SysGateRecordEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 86195
 * @version 1.0
 * @description TODO
 * @date 2023/9/20 15:52
 */
@Service
@Slf4j
public class PlateCallback implements IPlateCallback {

    @Autowired
    private SysGateService service;


    String[] strVehType = new String[] {
            "未知",
            "轿车",
            "面包车",
            "大型客车",
            "中型客车",
            "皮卡",
            "非机动车",
            "SUV",
            "MPV",
            "微型货车",
            "轻型货车",
            "中型货车",
            "重型货车"
    };
    String[] strVehColor = new String[] {"未知",
            "黑色",
            "蓝色",
            "灰色",
            "棕色",
            "绿色",
            "夜间深色",
            "紫色",
            "红色",
            "白色",
            "黄色"
    };
    String[] strVehDir = new String[] {"车头方向",
            "车尾方向",
            "车头车尾方向"
    };
    String[] strAlarmType = new String[] {
            "实时_硬触发+临时车辆",
            "实时_视频触发+临时车辆",
            "实时_软触发+临时车辆",
            "实时_硬触发+白名单",
            "实时_视频触发+白名单",
            "实时_软触发+白名单",
            "实时_硬触发+黑名单",
            "实时_视频触发+黑名单",
            "实时_软触发+黑名单",
            "脱机_硬触发+临时车辆",
            "脱机_视频触发+临时车辆",
            "脱机_软触发+临时车辆",
            "脱机_硬触发+白名单",
            "脱机_视频触发+白名单",
            "脱机_软触发+白名单",
            "脱机_硬触发+黑名单",
            "脱机_视频触发+黑名单",
            "脱机_软触发+黑名单",
            "实时_硬触发+过期白名单",
            "实时_视频触发+过期白名单",
            "实时_软触发+过期白名单",
            "脱机_硬触发+过期白名单",
            "脱机_视频触发+过期白名单",
            "脱机_软触发+过期白名单"
    };

    private Map<String,String> savePic(String strIP, String strNumber, byte[] data, int type, long lTime) throws Exception {
        Map res = new HashMap(2);
        String filePrefix = GateConstant.FILE_PREFIX + strIP;
//        String strPath = "D:/抓拍_java/";
        Date now = null;

        if(lTime == 0) {
            now = new Date();
        }
        else {
            now = new Date(lTime);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");


        String strPath = FileUtils.getFilePath(filePrefix);

        String dateNow2 = dateFormat.format(now);


//        strPath += strIP + "/" + dateNow;
        File file = new File(strPath);
        if(!file.exists())
        {
            file.mkdirs();
        }
        String filename = strPath + "/" + dateNow2 + "_" + strNumber;
        filename = filename.trim();

        if(1 == type)//plate
        {
            filename += "_plate";
        }
        filename += ".jpg";

        res.put(GateConstant.KEY_FILE_PATH,strPath);
        res.put(GateConstant.KEY_FILE_NAME,filename.substring(filename.lastIndexOf("/") + 1));

        try {
            DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
            out.write(data);
            out.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            throw new Exception("保持车牌相片异常");
        }

        return res;
    }


    @Override
    public void ICE_IPCSDK_Plate(int param, String strIP, String strNumber, String strColor, Pointer pPicData,
                                 int nLen, Pointer pCloseupData, int nCloseupLen, int nReserved1, int nVehicleType, int nFalsePlate,
                                 int nReserved2, float fPlateConfidence, int nVehicleColor, int nPlateType, int nVehicleDir,
                                 int nAlarmType, int nSerialNum, int nCapTime, int nReserved3, int nReserved4) {
        // TODO Auto-generated method stub

//            String strText = (param == 0 ? "[入口相机]:" : "[出口相机]:" ) + strIP + "," + strNumber + "," + strColor + ", " + (nVehicleType >= 0 && nVehicleType <= 12 ? strVehType[nVehicleType] : "")
//                    + ",虚假车牌:" + (nFalsePlate == 1 ? "是" : "否") + "," + fPlateConfidence + ",";
//            strText += (nVehicleColor >= -1 && nVehicleColor <= 9 ? strVehColor[nVehicleColor + 1] : "") + "," +(nVehicleDir >= 0 && nVehicleDir <= 2 ? strVehDir[nVehicleDir] : "")
//                    + ","+ (nAlarmType >= 0 && nAlarmType <= 23 ? strAlarmType[nAlarmType] : "");
        String gateName = GateConstant.GATE_NAME_MAP.get(strIP);
        if(GlobalConstant.COLOR_BLUE.equals(strColor)){
            //如果车牌底色为蓝色，车牌首字替换成“钢”字
            if(StringUtils.isNotEmpty(strNumber)){
                strNumber = GlobalConstant.CHINESE_GANG + strNumber.substring(1);
            }
        }

        String strText = gateName + strIP + "," + strNumber + "," + strColor + ", " + (nVehicleType >= 0 && nVehicleType <= 12 ? strVehType[nVehicleType] : "")
                + ",虚假车牌:" + (nFalsePlate == 1 ? "是" : "否") + "," + fPlateConfidence + ",";
        strText += (nVehicleColor >= -1 && nVehicleColor <= 9 ? strVehColor[nVehicleColor + 1] : "") + "," +(nVehicleDir >= 0 && nVehicleDir <= 2 ? strVehDir[nVehicleDir] : "")
                + ","+ (nAlarmType >= 0 && nAlarmType <= 23 ? strAlarmType[nAlarmType] : "");


        if(nLen > 0){
            byte[] dst = new byte[nLen];
            pPicData.read(0, dst, 0, nLen);
            try {

                Map<String,String> map = savePic(strIP, strNumber, dst, 0, 0);
//                jpegShow.jnaLib.jpegShow_showPic(jpegShowHandle[param], dst, nLen, hPic[param]);
                SysGateRecordEntity entity = SysGateRecordEntity.builder().detailsMsg(strText).carLicense(strNumber)
                        .gateName(gateName).filePath(map.get(GateConstant.KEY_FILE_PATH))
                        .status(GateRecordStatusEnum.STATUS_ABNORMAL.getStatus()) //初始化异常状态
                        .fileName(map.get(GateConstant.KEY_FILE_NAME)).build();
                //本地SDK与数据库交互，增加securityManager
                SecurityManager securityManager = new DefaultSecurityManager();
                SecurityUtils.setSecurityManager(securityManager);
                //判断对应车辆动作类型   进去还是出去
                GateActionEnum gateActionEnum = GateTypeEnum.getGateActionEnum(strIP);
                if(gateActionEnum == null){
                    return;
                }
                if(gateActionEnum.getType().equals("1")){
                    service.enter(entity);
                } else {
                    service.exit(entity);
                }

                dst = null;
            } catch (Exception e){
                //todo 异常记录日志
                log.error("保持相片异常",e);
            }
        }

        if(nCloseupLen > 0){
            byte[] dstPlate = new byte[nCloseupLen];
            pCloseupData.read(0, dstPlate, 0, nCloseupLen);
            try {
                savePic(strIP, strNumber, dstPlate, 1, 0);
                dstPlate = null;
            } catch (Exception e){

            }
        }

    }
}
